package com.feng.study.config.jackson;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.feng.study.aspect.EnumDict;
import com.feng.study.common.CodeEnum;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.util.Objects;

@Log4j2
public class EnumDictSourceJsonSerializer extends JsonSerializer<Object> {
    private final BeanPropertyWriter propertyWriter;

    EnumDictSourceJsonSerializer(BeanPropertyWriter propertyWriter) {
        this.propertyWriter = propertyWriter;
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        serializers.defaultSerializeValue(value, gen);
        String fieldNameValue = "";
        EnumDict dictData = propertyWriter.getAnnotation(EnumDict.class);
        if (Objects.nonNull(value)) {
            for (CodeEnum<?> enumConstant : dictData.enumType().getEnumConstants()) {
                if (Objects.equals(enumConstant.getCode(), value)) {
                    fieldNameValue = enumConstant.getName();
                    break;
                }
            }
        }
        String fieldNameKey = propertyWriter.getName().concat("Name");

        gen.writeStringField(fieldNameKey, StringUtils.isBlank(fieldNameKey)?dictData.defaultValue():fieldNameValue);
    }
}
